<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\SendMail;
use App\Model\HomeUserModel;
use App\Model\HomeUserCaptcha;
use App\Model\HomeUserBeforpass;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Home\ShowLinksController;
use App\Http\Controllers\Api\IndexApi;

class EmailGetReturnController extends Controller
{
    // 显示邮箱改密码页面
    public function EmailGetReturnPage(Request $request)
    {
        // 获取用户session信息
        $user = $request->session()->get('Homeuser-data');

        // 站点信息类
        $type = new IndexApi;
        $index = new ShowLinksController;

        // 获取站点信息
        $sate = IndexApi::getSate();
        $linksArray = $index->index();

        // 判断是否已登录
        if ($user) {
            // 判断是否已注册
            if (empty($user['email'])) {
                return redirect()->route('home.bindemail', ['id' => $user['id']])->with('message', '请先注册邮箱');
            }

            // 返回视图
            return view('Home.goods-emailchangepass', ['user' => $user, 'sate' => $sate, 'linksArray' => $linksArray]);
        }

        // 未登录返回视图
        return view('Home.goods-emailchangepass', ['sate' => $sate, 'linksArray' => $linksArray]);
    }

    // 发送邮箱验证码
    public function SendEmailCode(Request $request)
    {
        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
            ['captchaIndex', '=', $request->bindemail],
            ['type', '=', 5],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();

          if ($captcha) {

              // 判断是否手贱
              if ($captcha->validperiod > time()) {
                  return 403;
              }
          }

          // 获取用户信息
          $userinfo = HomeUserModel::select('username')->where('email', $request->bindemail)->first();

          // 得到对象
          $sendemail = new SendMail;

          $title = '您修改密码的验证码!';



          // 发送验证码
          $result = $sendemail->send($userinfo->username, $request->bindemail, $title);

          if ($result) {
              // 保存记录
              HomeUserCaptcha::insert([
                  'captchaIndex'=> $request->bindemail,
                  'captcha'     => $result['code'],
                  'validperiod' => $result['end_time'],
                  'type'        => 5,
              ]);
              return 123;
          }
    }

    // 验证验证码
    public function ValidataGetReturnCode(Request $request)
    {
        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
            ['captchaIndex', '=', $request->bindemail],
            ['type', '=', 5],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();
        // 判断是否有该用户的验证码
        if (!$captcha) {
            return 500;
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            return 403;
        }

        // 判断是否验证成功
        if ($request->code == $captcha->captcha) {
            return 200;
        }

        return 500;
    }

    // 处理表单
    public function EmailGetReturnForm(Request $request)
    {

        // 获取用户信息
        $mysqluser = HomeUserModel::select('id', 'username', 'sex', 'pic', 'email', 'member', 'phone', 'passname')
            ->where('email', $request->bindemail)->get();

        // 判断用户是否绑定邮箱
        if (empty($mysqluser[0]->email)) {
            return redirect()->route('home.emailgetreturn', ['id' => $mysqluser[0]->id])->with('message', '该邮箱未绑定，请先去绑定邮箱!');
        }

        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
            ['captchaIndex', '=', $request->bindemail],
            ['type', '=', 5],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();

        // 判断该用户是否非法
        if(empty($captcha)) {
            return redirect()->route('home.emailgetreturn', ['id' => $mysqluser[0]->id])->with('message', '服务器繁忙请重试!');
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            $result = HomeUserCaptcha::where([
                ['captchaIndex', '=',$request->bindemail],
                ['type', '=', 5],
            ])->delete();
            return redirect()->route('home.emailgetreturn', ['id' => $mysqluser[0]->id])->with('message', '验证码超时，请重新获取!');
        }

        // 判断是否验证成功
        if ($request->emailcode == $captcha->captcha) {
            // 准备键名
            $hashkey = 'home_user_hash_phone:'.$mysqluser[0]->phone;

            // 判断该用户是否存在
            if (isset($mysqluser[0])) {

              // 记录过去密码
              HomeUserBeforpass::insert([
                'user_id'    => $mysqluser[0]->id,
                'befor_pass' => $mysqluser[0]->passname,
              ]);

              // 更改密码
              HomeUserModel::where('id', $mysqluser[0]->id)
              ->update([
                    'passname' => password_hash($request->input('password'), PASSWORD_DEFAULT),
              ]);

                // 查找redis
                $redisuser = Redis::hGetAll($hashkey);

                // 判断是否存在
                if ($redisuser) {
                    // 删除redis用户
                    Redis::del($hashkey);
                    // 重新添加
                    $userinfo = Redis::hMSet($hashkey, [
                        'id'         => $redisuser['id'],
                        'username'   => $redisuser['username'],
                        'passname'   => password_hash($request->input('password'), PASSWORD_DEFAULT),
                        'sex'        => $redisuser['sex'],
                        'pic'        => $redisuser['pic'],
                        'email'      => $request->bindemail,
                        'phone'      => $redisuser['phone'],
                        'user_status'=> $redisuser['user_status'],
                        'member'     => $redisuser['member'],
                        'created_at' => $redisuser['created_at'],
                    ]);
                }

                // 删除无效验证码
                $result = HomeUserCaptcha::where([
                    ['captchaIndex', '=',$request->phone],
                    ['type', '=', 2],
                ])->delete();
                // 退出登录
                $request->session()->forget('Homeuser-data');
                return redirect()->route('home.login');
            } else {
                // 找不到用户
                return redirect()->route('home.emailgetreturn', ['id' => $user->id])->with('message', '服务请繁忙，请重试');
            }

        } else {
            // 验证码错误
            return redirect()->route('home.emailgetreturn', ['id' => $user->id])->with('message', '验证码错误请重试');
        }
    }
}
